package com.csdig.cms.web.admin;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.csdig.cms.common.ConstantDefine;
import com.csdig.cms.model.ModelItem;
import com.csdig.cms.model.binder.ModelItemBinder;
import com.csdig.cms.service.CmsResourceMng;
import com.csdig.cms.service.ModelService;

@Controller
@RequestMapping(value = ConstantDefine.AdminUrl.BASE + "/model")
public class ModelController {

	@Autowired
	private ModelService modelService;
	
	@Autowired
	private CmsResourceMng resourceMng;

	@RequestMapping(value = "/{name}View")
	public String list(@PathVariable String name) throws Exception {
		return "model/" + name;
	}

	@RequestMapping(value = "/editView")
	public String editView(HttpServletRequest request, String id) throws Exception {
		String content = resourceMng.readFile(id);
		List<ModelItem> list = modelService.findModelItemByPath(id);
		request.setAttribute("list", list);
		request.setAttribute("content", content);
		request.setAttribute("file", resourceMng.getFile(id));
		return "model/edit";
	}
	
	
	@RequestMapping(value = "saveSubItem")
	@ResponseBody
	public Map<String, Object> saveSubItem(String modelPath, String tplTxt, ModelItemBinder items)
			throws Exception {
		modelService.saveItems(modelPath,tplTxt,items);
		Map<String, Object> result = new HashMap<String, Object>();
		return result;
	}

}
